/**
 * 读取csv文件并解析
 */
const csvParser = require('csv-parser');
const fs = require('fs');
const { join } = require('path');
const dayjs = require('dayjs');

async function readAndParseCSV(filePath) {
  const results = [];
  return new Promise((resolve, reject) => {
    fs.createReadStream(filePath)
      .pipe(csvParser())
      .on('data', (data) => results.push(data))
      .on('end', () => {
        resolve(results);
      })
      .on('error', (error) => {
        reject(error);
      });
  });
}

class DaylayItem {
  list = new Map();
  count = 0;
  set(link, name, count) {
    this.count = this.count + 1;
    const item = this.list.get(name);
    if (item) {
      item.count += parseInt(count);
      this.list.set(name, item);
    } else {
      this.list.set(name, { link, name, count: parseInt(count) });
    }
  }
  toList() {
    const items = [];
    this.list.forEach((item) => {
      items.push(item);
    });
    return items.sort((a, b) => b.count - a.count);
  }
  toJson() {
    const list = this.toList();
    return {
      count: this.count,
      total: list.length,
      list: list,
    };
  }
}
class Daylay {
  hours = new Map();
  addItem(hour, link, name, count) {
    const h = this.hours.get(hour) || new DaylayItem();
    h.set(link, name, count);
    this.hours.set(hour, h);
  }
  toJson() {
    const json = {};
    this.hours.forEach((item, key) => {
      json[key] = item.toJson();
    });
    return json;
  }
}
readAndParseCSV(join(__dirname, 'zbxinxi_202403142213.csv'))
  .then((res) => {
    const daylay = new Daylay();
    res.map((it) => {
      const { lianjie, htzh, bssl, time, nicheng } = it;
      const openTime = dayjs(time).add(8, 'hour').format('HH');
      daylay.addItem(openTime, lianjie, nicheng, bssl);
    });
    return daylay.toJson();
  })
  .then((res) => {
    fs.writeFileSync(
      join(__dirname, 'daylay.json'),
      JSON.stringify(res, null, 2),
    );
  });
